package com.itwn.portal.interceptor;

import com.itwn.portal.common.exception.Asserts;
import com.itwn.portal.common.result.BusinessCode;
import com.itwn.portal.common.result.ResultCode;
import com.itwn.portal.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在执行控制器方法之前执行，一般用来做一些校验操作
     */
    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器:{}",request.getRequestURI());

        //1. 判断是否是options请求，如果是则直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        //2. 获取请求头
        String token = request.getHeader("Authorization");

        //3. 判断token是否存在
        Asserts.error(Objects.isNull(token), BusinessCode.TOKEN_NOT_EXISTS);

        //4. 验证token是否有效
        Asserts.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);

        //5. 判断IP地址是否相同
        String remoteAddr = jwtUtil.getRequestIP(request);
        String tokenIp = jwtUtil.getValue(token, "ip");
        Asserts.error(!remoteAddr.equals(tokenIp), BusinessCode.INVALID_IP);

        //6. 如果都通过则放行
        return true;
    }
}
